package com.mqdemo.service.impl;

import cn.hutool.core.lang.UUID;
import com.mqdemo.dto.Result;
import com.mqdemo.service.BaiduAIService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

import static com.mqdemo.utils.SystemConstants.HOST;

@Slf4j
@Service
public class BaiduAIServiceImpl implements BaiduAIService {

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Value("${web.upload-path}")
    private String uploadPath;
    @Override
    public Result actionOcr(MultipartFile multipartFile, String uuid) {
        if (multipartFile == null) {
            return Result.fail("图片不能为空");
        }
        // 处理图片保存到本地Resources-images路径

        String fileUrl = null;
        try {
            String originalFileName = multipartFile.getOriginalFilename();
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            String storedFileName = UUID.randomUUID().toString(true) + fileExtension;
            Path destinationFile = Paths.get(uploadPath, storedFileName).toAbsolutePath().normalize();

            multipartFile.transferTo(destinationFile);

            fileUrl = "http://"+HOST+":8080/images/" + storedFileName;
        } catch (IOException e) {
            log.error("文件存取异常，{}", e.getMessage());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("uuid", uuid);
        map.put("file_url", fileUrl);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        rabbitTemplate.convertAndSend("baidu.ai.mq", map);
        log.info("MQ添加成功", uuid);
        return Result.ok(map);
    }
}
